//
//  BaseTabBarController.m
//  worthVote
//
//  Created by kingboyrang on 2021/4/12.
//  Copyright © 2021 wulanzhou. All rights reserved.
//

#import "BaseTabBarController.h"
#import "BaseNavigationController.h"
#import "UIImage+CZExtend.h"
#import "CTTabBarItem.h"


#define KBarItemHeight 49.0f

@interface BaseTabBarController ()<UITabBarControllerDelegate,UINavigationControllerDelegate>{
    NSInteger selectIndex;
    BOOL     tabBarIsShow;
}
/** 背景 */
@property (nonatomic,strong) UIView *tabBarBg;

@end

@implementation BaseTabBarController

- (instancetype)init {
    if(self = [super init]) {
        selectIndex = 0;
        tabBarIsShow = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    selectIndex = 0;
    tabBarIsShow = YES;
    //隐藏系统uitabbar
    [self hideSystemTabbar];
    //添加自定义TabBar
    [self.view addSubview:self.tabBarBg];
    // Do any additional setup after loading the view.
}
#pragma mark - 属性
/**
*  设置TabBar背景颜色
*  @param backgroudColor 背景颜色
*/
- (void)setTabBarBackGroundColor:(UIColor *)backgroudColor{
    self.tabBarBg.backgroundColor = backgroudColor;
}
- (UIView *)tabBarBg{
    if (_tabBarBg == nil) {
        _tabBarBg = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.height-kTabbarRealHeight, kScreenWidth, kTabbarRealHeight)];
        _tabBarBg.backgroundColor =[UIColor colorFromHexRGB:@"f44336"];
        
        /**
        //画线
       UILabel *labLine=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.5)];
       labLine.backgroundColor=[UIColor colorFromHexRGB:@"D32F2F"];
       [_tabBarBg addSubview:labLine];
         */
    }
    return _tabBarBg;
}

- (void)setItems:(NSArray<BarItemModel *> *)items
{
    if (_items!=items) {
        _items = items;
        NSAssert((items != nil && [items count]>0), @"至少设置一个tabbar");
        [self createTabBarWithItems:items];
    }
}

#pragma mark - 私有方法
// 初始化所有子控制器
- (void)createTabBarWithItems:(NSArray<BarItemModel *> *)items{
    typeof(self) __weak weakSelf = self;
    [items enumerateObjectsUsingBlock:^(BarItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        BaseNavigationController* nav = [[BaseNavigationController alloc] initWithRootViewController:obj.viewController];
        obj.viewController.title  = obj.title;
        nav.delegate = weakSelf;
        [weakSelf addChildViewController:nav];
    }];
    //创建自定义的tabbar
    [self createCustomTabbar];
}
//创建自定义的tabbar
- (void)createCustomTabbar {
    
    typeof(self) __weak weakSelf = self;
    CGFloat itemWith = self.view.width/[self.items count];
    [weakSelf.items enumerateObjectsUsingBlock:^(BarItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        
        CTTabBarItem * homeBtn = [[CTTabBarItem alloc]initWithFrame:CGRectMake(idx*itemWith, 0 , itemWith, KBarItemHeight)];
        homeBtn.tag = idx;
        [homeBtn setNormalImage:[UIImage imageNamed:obj.normalImage]
                  selectedImage:[UIImage imageNamed:obj.selectedImage]
                          title:obj.title
         normalTitleColor:obj.normalColor selectedTitleColor:obj.selectedColor]; //tab_keypad_down  tab_keypad_up
        
        [homeBtn addTarget:weakSelf action:@selector(tabBarBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [weakSelf.tabBarBg addSubview:homeBtn];
        if (idx == 0) {
            homeBtn.selected = YES;
        }
        
    }];
}
//隐藏系统的tabbar
- (void)hideSystemTabbar {
    if ( [self.view.subviews count] < 2 ) {
        return;
    }
    
    UIView *contentView;
    if ( [[self.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] ) {
        contentView = [self.view.subviews objectAtIndex:1];
    } else {
        contentView = [self.view.subviews objectAtIndex:0];
    }
    BOOL hide=YES;
    if (hide) {
       
        contentView.frame = self.view.bounds;
    } else {
        contentView.frame = CGRectMake(self.view.bounds.origin.x,
                                       self.view.bounds.origin.y,
                                       self.view.bounds.size.width,
                                       self.view.bounds.size.height -
                                       kTabbarRealHeight);
    }
    
    for(UIView *view in self.view.subviews) {
        if([view isKindOfClass:[UITabBar class]]) {
            view.hidden = YES;
            break;
        }
    }
}
#pragma mark - 自定义tabbar按钮点击事件
- (void)tabBarBtnClick:(CTTabBarItem *)btn {
    if(btn.tag != selectIndex) {
        for(UIView *view in self.tabBarBg.subviews) {
            if([view isKindOfClass:[UIButton class]]) {
                CTTabBarItem *button = (CTTabBarItem *)view;
                button.selected = NO;
            }
        }
        btn.selected = YES;
        selectIndex = btn.tag;
        self.selectedIndex=btn.tag;
        //点击tabBarItem放大效果
        [self addAminal:btn];
    }
}
//点击tabBarItem放大效果
- (void)addAminal:(CTTabBarItem *)btn{
    CABasicAnimation *pulse = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    pulse.timingFunction= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pulse.duration = 0.08;
    pulse.repeatCount= 1;
    pulse.autoreverses= YES;
    pulse.fromValue= [NSNumber numberWithFloat:0.7];
    pulse.toValue= [NSNumber numberWithFloat:1.3];
    [[btn layer] addAnimation:pulse forKey:nil];
}
#pragma mark -公有方法

/**
 *  设置选中tabItem项
 *
 *  @param index 选中的第几个tab
 */
- (void)selectedItemTabBarIndex:(NSInteger)index {
    for(UIView *view in self.tabBarBg.subviews) {
        if([view isKindOfClass:[CTTabBarItem class]]) {
            CTTabBarItem *button = (CTTabBarItem *)view;
            if (index==button.tag) {
                [self tabBarBtnClick:button];
                break;
            }
        }
    }
}

//显示微章
- (void)showBadgeValue:(NSString*)badgeValue index:(NSInteger)index {
    for(UIView *view in self.tabBarBg.subviews) {
        if([view isKindOfClass:[CTTabBarItem class]]) {
            CTTabBarItem *button = (CTTabBarItem *)view;
            if (button.tag==index) {
                [button showBadgeValue:badgeValue];
                break;
            }
        }
    }
}

//移除微章
- (void)removeBadgeValueWithIndex:(NSInteger)index {
    for(UIView *view in self.tabBarBg.subviews) {
        if([view isKindOfClass:[CTTabBarItem class]]) {
            CTTabBarItem *button = (CTTabBarItem *)view;
            if (button.tag==index) {
                [button removeBadgeValue];
                break;
            }
        }
    }
}

//显示红点
- (void)showBadgeWithIndex:(NSInteger)index {
    for(UIView *view in self.tabBarBg.subviews) {
        if([view isKindOfClass:[CTTabBarItem class]]) {
            CTTabBarItem *button = (CTTabBarItem *)view;
            if (button.tag==index) {
                [button showBadge];
                break;
            }
        }
    }
}

//删除红点
- (void)removeBadgeWithIndex:(NSInteger)index {
    for(UIView *view in self.tabBarBg.subviews) {
        if([view isKindOfClass:[CTTabBarItem class]]) {
            CTTabBarItem *button = (CTTabBarItem *)view;
            if (button.tag==index) {
                [button removeBadge];
                break;
            }
        }
    }
}
/**
- (void)modifyTabBarFrame {
    CGRect r = self.tabBarBg.frame;
    r.origin.y = kScreenHeight-kTabbarRealHeight;
    self.tabBarBg.frame = r;
    self.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-kTabbarRealHeight);
}

- (void)restoreTabBarFrame {
    CGRect r = self.tabBarBg.frame;
    r.origin.y = kScreenHeight-kTabbarRealHeight-kNavigationBarRealHeight;
    self.tabBarBg.frame = r;
    
    self.view.frame = CGRectMake(0.0f, 0.0f, kScreenWidth, kScreenHeight-kTabbarRealHeight-kNavigationBarRealHeight);
}
 */

- (void)hideTabBar {
    if (!tabBarIsShow)
    {
        return;
    }
    [UIView animateWithDuration:0.2
                     animations:^{
                         CGRect tabFrame = self.tabBarBg.frame;
                         tabFrame.origin.x = 0 - tabFrame.size.width;
                         self.tabBarBg.frame = tabFrame;
                     }];
    tabBarIsShow = NO;
}

- (void)showTabBar {
    if (tabBarIsShow)
    {
        return;
    }
    /**
    [UIView animateWithDuration:0.3
                     animations:^{
                         
                         CGRect tabFrame = self.tabBarBg.frame;
                         tabFrame.origin.x = CGRectGetWidth(tabFrame) + CGRectGetMinX(tabFrame);
                         self.tabBarBg.frame = tabFrame;
                         [self.view bringSubviewToFront:self.tabBarBg];
                     }];
     */
    
    CGRect tabFrame = self.tabBarBg.frame;
    tabFrame.origin.x = CGRectGetWidth(tabFrame) + CGRectGetMinX(tabFrame);
    self.tabBarBg.frame = tabFrame;
    [self.view bringSubviewToFront:self.tabBarBg];
    tabBarIsShow = YES;
}
#pragma mark -UINavigationControllerDelegate Methods
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{

    if (navigationController.viewControllers.count >1) {
        [self hideTabBar];
        //[[NSNotificationCenter defaultCenter] postNotificationName:kTabbarCenterHideNotification object:nil];
    }

    if (navigationController.viewControllers.count == 1) {
        [self showTabBar];
        // [[NSNotificationCenter defaultCenter] postNotificationName:kTabbarCenterShowNotification object:nil];
    }
   
}
@end
